package com.gm.corejava.book2;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-12-26
 * Time: 上午10:34
 * To change this template use File | Settings | File Templates.
 */
public class ColorTableCellEditor extends AbstractCellEditor implements TableCellEditor {

    public ColorTableCellEditor() {
        panel=new JPanel();


        colorChooser=new JColorChooser();
        colorDialog=JColorChooser.createDialog(null,"Planet Color",false,colorChooser,new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopCellEditing();
            }
        },new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        cancelCellEditing();
                    }
                });

        colorDialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                cancelCellEditing();
            }
        });
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        colorChooser.setColor((Color)value);;
        return panel;
    }

    @Override
    public Object getCellEditorValue() {
        return colorChooser.getColor();
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        colorDialog.setVisible(true);
        return true;
    }

    @Override
    public boolean stopCellEditing() {
        colorDialog.setVisible(false);
        super.stopCellEditing();
        return true;
    }

    @Override
    public void cancelCellEditing() {
        colorDialog.setVisible(false);
        super.cancelCellEditing();    //To change body of overridden methods use File | Settings | File Templates.
    }

    private JColorChooser colorChooser;
    private JDialog colorDialog;
    private JPanel panel;
}
